﻿using CoreShop.Model;
using CoreShop.Services;
using FastMember;
using SqlSugar.Extensions;
using Sunny.UI;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CoreShop.Library;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Net.NetworkInformation;
using static CoreShop.Library.GlobalEnumVars;
using System.Reflection;
using System.Threading;
using SqlSugar;
using System.Runtime.Remoting.Messaging;
using CoreShop.Model.OrderModels;

namespace CoreShop.PrintService
{
    public class PrintServices
    {
        private corecmsprintscheme printscheme = null;
        private Menu menu;
        private object MenuObj;
        private object DataObj;
        private object DataTotalObj;
        private string _printerIP = "";
        private bool _PrinterState = false;

        private void ClearPrintObject()
        {
            MenuObj = null;
            DataObj = null;
            DataTotalObj = null;
        }

        public string IPAddress { get => _printerIP; set => _printerIP = value; }
        public bool GetPrinterState { get => _PrinterState; set => _PrinterState = value; }
        public corecmsprintscheme PrintSchemeInfo { get => printscheme; set => printscheme = value; }

        #region 打印处理        
        /// <summary>
        /// 获取并打印数据
        /// </summary>
        public bool SetTaskDetailPrint(bool ret)
        {
            bool isOpenPrinter = false;
            try
            {
                //mut_printer.WaitOne();
                List<corecmsprinttaskdetail> taskDetails = new corecmsprinttaskdetailServices().QueryPrintTaskDetail(printscheme.id);
                if ((taskDetails == null) || (taskDetails.Count == 0))
                {
                    if ((!ret) && (printscheme.sendPrintWay == (int)GlobalEnumVars.SendPrintWay.Command || printscheme.sendPrintWay == (int)GlobalEnumVars.SendPrintWay.KDS_Bestone)
                        && (!new PingPrinter().PingIPAddress(printscheme.printerIP))) return false;
                    return true;
                }

                var batchIds = taskDetails.Select(x => x.batchId).ToList().Distinct().ToList();

                if ((!ret) && (printscheme.sendPrintWay == (int)GlobalEnumVars.SendPrintWay.Command || printscheme.sendPrintWay == (int)GlobalEnumVars.SendPrintWay.KDS_Bestone)
                    && (!new PingPrinter().PingIPAddress(printscheme.printerIP))) return false;

                if ((printscheme.sendPrintWay == (int)GlobalEnumVars.SendPrintWay.Command) && !OpenNetPrint()) return false;//打开打印机（芯烨有效）
                isOpenPrinter = true;
                if (printscheme.sendPrintWay == (int)GlobalEnumVars.SendPrintWay.Drive) ret = true;
                foreach (var batchId in batchIds)
                {
                    var newRet = true;
                    var dataDetails = taskDetails.Where(p => p.batchId == batchId).ToList();
                    if ((dataDetails == null) || (dataDetails.Count == 0)) continue;
                    switch (printscheme.sendPrintWay)
                    {
                        case (int)GlobalEnumVars.SendPrintWay.Command://指令打印
                            var dataDetail = dataDetails.First();
                            var schemedetail = printscheme.printschemedetails.Find(p => p.billtypeId == dataDetail.billtypeId);
                            if (schemedetail == null) continue;
                            var billtemplate = schemedetail.billtemplate;
                            if (billtemplate == null) continue;

                            //IP指令打印
                            if ((billtemplate.foodPrintType == (int)GlobalEnumVars.foodPrintType.Order) ||
                            (billtemplate.foodPrintType == (int)GlobalEnumVars.foodPrintType.Summary))
                                newRet = SetPrintKitchenByList(dataDetails, billtemplate);
                            else
                                newRet = SetPrintKitchenByOne(dataDetails, billtemplate);
                            break;
                        case (int)GlobalEnumVars.SendPrintWay.Drive:
                            new ReportServices().SetPrinKitchen(dataDetails, printscheme);//驱动打印
                            break;
                        default:
                            break;

                    }
                    if (!newRet) ret = false;
                }
            }
            catch (Exception ex) { }
            finally
            {
                if (isOpenPrinter) CloseNetPrint();//关闭
            }
            return ret;
        }


        /// <summary>
        /// 获取并打印数据(异步处理)
        /// </summary>
        public async Task<bool> SetTaskDetailPrintAsync()
        {
            bool ret = true;
            bool isOpenPrinter = false;
            try
            {
                //mut_printer.WaitOne();
                List<corecmsprinttaskdetail> taskDetails = new corecmsprinttaskdetailServices().QueryPrintTaskDetail(printscheme.id);
                if ((taskDetails == null) || (taskDetails.Count == 0)) return true;

                var batchIds = taskDetails.Select(x => x.batchId).ToList().Distinct().ToList();

                if (await OpenNetPrintAsync() == false) return false;//打开打印机（芯烨有效）

                isOpenPrinter = true;
                foreach (var batchId in batchIds)
                {
                    var newRet = true;
                    var dataDetails = taskDetails.Where(p => p.batchId == batchId).ToList();
                    if ((dataDetails == null) || (dataDetails.Count == 0)) continue;
                    if (printscheme.sendPrintWay == (int)GlobalEnumVars.SendPrintWay.Command)
                    {
                        var dataDetail = dataDetails.First();
                        var schemedetail = printscheme.printschemedetails.Find(p => p.billtypeId == dataDetail.billtypeId);
                        if (schemedetail == null) continue;
                        var billtemplate = schemedetail.billtemplate;
                        if (billtemplate == null) continue;

                        //IP指令打印
                        if ((billtemplate.foodPrintType == (int)GlobalEnumVars.foodPrintType.Order) ||
                        (billtemplate.foodPrintType == (int)GlobalEnumVars.foodPrintType.Summary))
                            newRet = SetPrintKitchenByList(dataDetails, billtemplate);
                        else
                            newRet = SetPrintKitchenByOne(dataDetails, billtemplate);
                    }
                    else
                        new ReportServices().SetPrinKitchen(dataDetails, printscheme);//驱动打印
                    if (!newRet) ret = false;
                }
            }
            catch (Exception ex) { }
            finally
            {
                if (isOpenPrinter) CloseNetPrint();//关闭
            }
            return ret;
        }

        #endregion

        #region 备用打印处理        
        /// <summary>
        /// 获取并打印数据
        /// </summary>
        public bool SetTaskDetailPrintSpare(bool isLink)
        {
            bool ret = isLink;
            try
            {
                List<corecmsprinttaskdetail> taskDetails = new corecmsprinttaskdetailServices().QueryPrintTaskDetailSpare(printscheme.id);
                if ((taskDetails == null) || (taskDetails.Count == 0)) return ret;
                var batchIds = taskDetails.Select(x => x.batchId).ToList().Distinct().ToList();//Distinct去重复相同的

                foreach (var batchId in batchIds)
                {
                    var newRet = true;
                    var dataDetails = taskDetails.Where(p => p.batchId == batchId).ToList();
                    if ((dataDetails == null) || (dataDetails.Count == 0)) continue;
                    if (printscheme.sendPrintWay == (int)GlobalEnumVars.SendPrintWay.Command)
                    {
                        var dataDetail = dataDetails.First();
                        var schemedetail = printscheme.printschemedetails.Find(p => p.billtypeId == dataDetail.billtypeId);
                        if (schemedetail == null) continue;
                        var billtemplate = schemedetail.billtemplate;
                        if (billtemplate == null) continue;

                        //IP指令打印
                        if ((billtemplate.foodPrintType == (int)GlobalEnumVars.foodPrintType.Order) ||
                        (billtemplate.foodPrintType == (int)GlobalEnumVars.foodPrintType.Summary))
                            newRet = SetPrintKitchenByList(dataDetails, billtemplate);
                        else
                            newRet = SetPrintKitchenByOne(dataDetails, billtemplate);
                    }
                    else
                        new ReportServices().SetPrinKitchen(dataDetails, printscheme);//驱动打印
                    if (!newRet) ret = false;
                }
            }
            catch (Exception ex) { }
            return ret;
        }
        #endregion

        #region 打印机操作IP
        /// <summary>
        /// 打开打印机
        /// </summary>
        /// <returns></returns>
        public bool OpenPrinter()
        {
            bool retsult = false;
            if (printscheme == null) return false;
            try
            {
                switch (printscheme.brandId)
                {
                    case (int)GlobalEnumVars.PrinterBrand.XinYe:
                        if (PrinterManager.xyPrinter == null) PrinterManager.xyPrinter = new XyPrinter();//芯烨打印机
                        PrinterManager.xyPrinter.m_Inited = PrinterManager.xyPrinter.ConnectNetPort(_printerIP);
                        if ((int)PrinterManager.xyPrinter.m_Inited > 0) retsult = true;
                        _PrinterState = retsult;
                        break;
                    default:
                        if (PrinterManager.jsPrinter == null) PrinterManager.jsPrinter = new JsPrinter();//通用打印机
                        if (PrinterManager.jsPrinter.OpenNetSev())
                        {
                            PrinterManager.jsPrinter.m_Inited = PrinterManager.jsPrinter.ConnectNetPort(_printerIP);
                        }
                        if (PrinterManager.jsPrinter.m_Inited > 0) retsult = true;
                        _PrinterState = retsult;
                        break;
                }
            }
            catch (Exception ex)
            {
            }
            return retsult;
        }

        /// <summary>
        /// ping打印机
        /// </summary>
        /// <param name="ipAddr"></param>
        /// <returns></returns>
        public Boolean PingNetSev(string ipAddr)
        {
            try
            {
                Ping p1 = new Ping();
                PingReply reply = p1.Send(ipAddr, 200); //发送主机名或Ip地址
                if (reply.Status == IPStatus.Success) return true;
                return false;
            }
            catch { return false; }
        }

        /// <summary>
        /// 关闭打印机
        /// </summary>
        /// <returns></returns>
        public bool ClosePrinter()
        {
            bool retsult = true;
            try
            {
                switch (printscheme.brandId)
                {
                    case (int)GlobalEnumVars.PrinterBrand.XinYe:
                        if (PrinterManager.xyPrinter != null) PrinterManager.xyPrinter.CloseNetPor();
                        break;
                    default:
                        if (PrinterManager.jsPrinter != null) PrinterManager.jsPrinter.CloseNetPor();
                        break;
                }
            }
            catch (Exception ex)
            {
            }
            return retsult;
        }

        /// <summary>
        /// 生成打印数据IP
        /// </summary>
        /// <param name="taskdetail"></param>
        /// <returns></returns>
        public MenuObject GetMenuObject(corecmsprinttaskdetail taskdetail)
        {
            var obj = new MenuObject();
            obj.Number = taskdetail.rowId.ToString();
            obj.FoodName = taskdetail.name.ToString();
            obj.OrderID = taskdetail.orderNo.ToString();
            obj.Person = taskdetail.person.ToString() + "人";
            obj.TableID = taskdetail.deskName.ToString();
            obj.CreateTime = taskdetail.createTime.ToString("yyyy-MM-dd HH:mm:ss");
            obj.DateTime = DateTime.Now.DateTimeString();
            obj.TaskName = string.IsNullOrEmpty(taskdetail.taskTitle) ? "" : "做法:" + taskdetail.taskTitle;
            obj.FeedName = string.IsNullOrEmpty(taskdetail.feedTitle) ? "" : "加料:" + taskdetail.feedTitle;
            obj.FQuantity = taskdetail.quantity.ToString("0.##") + taskdetail.specName;
            obj.Amount = taskdetail.amount.ObjToString();
            obj.RealAmount = taskdetail.realAmount.ObjToString();
            obj.TaskAmount = taskdetail.taskAmount.ObjToString();
            obj.FeedAmount = taskdetail.feedAmount.ObjToString();
            obj.AllAmount = taskdetail.allAmount.ObjToString();
            obj.SumQuantity = taskdetail.sumQuantity.ObjToString();
            obj.SumAmount = taskdetail.sumAmount.ObjToString();
            obj.SumRealAmount = taskdetail.sumRealAmount.ObjToString();
            obj.SumTaskAmount = taskdetail.sumTaskAmount.ObjToString();
            obj.SumFeedAmount = taskdetail.sumFeedAmount.ObjToString();
            obj.SumDisAmount = taskdetail.sumDisAmount.ObjToString();
            obj.SumAllAmount = taskdetail.sumAllAmount.ObjToString();
            obj.Remark = string.IsNullOrEmpty(taskdetail.detailRemark) ? "" : "备注:" + taskdetail.detailRemark;
            obj.FoodNumber = taskdetail.number.ObjToString();
            obj.Parcel = taskdetail.parcel.ObjToString();
            obj.Operator = taskdetail.billerName.ObjToString();
            obj.CallType = taskdetail.callType.ObjToString();
            obj.BillTitle = taskdetail.billTitle.ObjToString();
            //以下结帐小票才有值
            obj.DisAmount = taskdetail.discount.ToString();
            obj.MemberName = "";
            obj.MemberPhone = "";
            obj.Address = "";
            obj.OrderRemark = string.IsNullOrEmpty(taskdetail.remark) ? "" : "备注:" + taskdetail.remark;
            obj.foodPackName = taskdetail.foodPackName.ObjToString();
            return obj;
        }

        /// <summary>
        /// 生成打印数据IP
        /// </summary>
        /// <param name="taskdetail"></param>
        /// <returns></returns>
        public MenuObject GetMenuObjectSub(string strName)
        {
            string mStr = "";
            var obj = new MenuObject();
            obj.Number = mStr;
            obj.FoodName = strName;
            obj.OrderID = mStr;
            obj.Person = mStr;
            obj.TableID = mStr;
            obj.CreateTime = mStr;
            obj.DateTime = mStr;
            obj.TaskName = mStr;
            obj.FeedName = mStr;
            obj.FQuantity = mStr;
            obj.Amount = mStr;
            obj.RealAmount = mStr;
            obj.TaskAmount = mStr;
            obj.FeedAmount = mStr;
            obj.AllAmount = mStr;
            obj.SumQuantity = mStr;
            obj.SumAmount = mStr;
            obj.SumRealAmount = mStr;
            obj.SumTaskAmount = mStr;
            obj.SumFeedAmount = mStr;
            obj.SumDisAmount = mStr;
            obj.SumAllAmount = mStr;
            obj.Remark = mStr;
            obj.FoodNumber = mStr;
            obj.Parcel = mStr;
            obj.Operator = mStr;
            obj.CallType = mStr;
            obj.BillTitle = mStr;
            obj.DisAmount = mStr;
            obj.MemberName = "";
            obj.MemberPhone = "";
            obj.Address = "";
            obj.OrderRemark = mStr;
            return obj;
        }

        #endregion

        #region 发送打印机(IP)


        /// <summary>
        /// 通用打印机
        /// </summary>
        /// <param name="_MenuObj"></param>
        /// <param name="_dataObj"></param>
        /// <param name="_dataTotalObj"></param>
        /// <param name="_menu"></param>
        /// <returns></returns>
        public bool SetPrintData(object _MenuObj, object _dataObj, object _dataTotalObj, Menu _menu)
        {
            bool retsult = false;
            try
            {
                MenuObj = _MenuObj;
                DataObj = _dataObj;
                DataTotalObj = _dataTotalObj;
                menu = _menu;
                if (!SetRowHeight(1)) return false;
                if (!PrintLines(menu.Header)) return false;
                PrintData(menu.Center);
                PrintLines(menu.Footer);
                SetCutPaper();
                SetBuzzing();
                retsult = true;
            }
            catch (Exception ex) { }
            return retsult;
        }

        public bool SetPrintTestPage()
        {
            bool retsult = false;
            try
            {
                if (!OpenNetPrint()) return false;
                switch (printscheme.brandId)
                {
                    case (int)GlobalEnumVars.PrinterBrand.XinYe:
                        retsult = PrinterManager.xyPrinter.PrintTestPage();
                        CloseNetPrint();
                        break;
                    default:
                        if (!OpenNetPrint()) return false;
                        if (PrinterManager.jsPrinter.m_Inited > 0) PrinterManager.jsPrinter.PrintTestPage();
                        if (PrinterManager.jsPrinter.m_Inited > 0) retsult = true;
                        break;
                }
            }
            catch (Exception ex) { }
            return retsult;
        }


        /// <summary>
        /// 打开网口打印机，芯烨每次打印前打印
        /// </summary>
        /// <returns></returns>
        public bool OpenNetPrint()
        {
            bool retsult = false;
            try
            {
                switch (printscheme.brandId)
                {
                    case (int)GlobalEnumVars.PrinterBrand.XinYe:
                        if (PrinterManager.xyPrinter == null)
                            PrinterManager.xyPrinter = new XyPrinter();
                        else LoadPOSDll.POS_Close();
                        PrinterManager.xyPrinter.PosPrint = new LoadPOSDll();
                        if (PrinterManager.xyPrinter.PosPrint.OpenNetPort(printscheme.printerIP))//当参数nParam的值为POS_OPEN_NETPORT时，表示打开指定的网络接口，如“192.168.10.251”表示网络接口IP地址，打印时参考
                        {
                            PrinterManager.xyPrinter.Gp_IntPtr = LoadPOSDll.POS_IntPtr;
                            if ((int)PrinterManager.xyPrinter.Gp_IntPtr > 0) retsult = true;
                        }
                        break;
                    default:
                        if (PrinterManager.jsPrinter == null)
                            PrinterManager.jsPrinter = new JsPrinter();//通用打印机
                        else PrinterManager.jsPrinter.CloseNetPor();
                        if (PrinterManager.jsPrinter.OpenNetSev())
                        {
                            PrinterManager.jsPrinter.m_Inited = PrinterManager.jsPrinter.ConnectNetPort(_printerIP);
                            if (PrinterManager.jsPrinter.m_Inited > 0) retsult = true;
                        }
                        break;
                }
            }
            catch (Exception ex) { }
            printscheme.Linked = retsult;
            return retsult;
        }

        /// <summary>
        /// 打开网口打印机，芯烨每次打印前打印
        /// </summary>
        /// <returns></returns>
        public async Task<bool> OpenNetPrintAsync()
        {
            bool retsult = false;
            try
            {
                switch (printscheme.brandId)
                {
                    case (int)GlobalEnumVars.PrinterBrand.XinYe:
                        if (PrinterManager.xyPrinter == null)
                            PrinterManager.xyPrinter = new XyPrinter();
                        else LoadPOSDll.POS_Close();
                        PrinterManager.xyPrinter.PosPrint = new LoadPOSDll();
                        if (await PrinterManager.xyPrinter.PosPrint.OpenNetPortAsync(printscheme.printerIP))//当参数nParam的值为POS_OPEN_NETPORT时，表示打开指定的网络接口，如“192.168.10.251”表示网络接口IP地址，打印时参考
                        {
                            PrinterManager.xyPrinter.Gp_IntPtr = LoadPOSDll.POS_IntPtr;
                            if ((int)PrinterManager.xyPrinter.Gp_IntPtr > 0) retsult = true;
                        }
                        break;
                    default:
                        if (PrinterManager.jsPrinter == null)
                            PrinterManager.jsPrinter = new JsPrinter();//通用打印机
                        else PrinterManager.jsPrinter.CloseNetPor();
                        if (PrinterManager.jsPrinter.OpenNetSev())
                        {
                            PrinterManager.jsPrinter.m_Inited = PrinterManager.jsPrinter.ConnectNetPort(_printerIP);
                            if (PrinterManager.jsPrinter.m_Inited > 0) retsult = true;
                        }
                        break;
                }
            }
            catch (Exception ex) { }
            printscheme.Linked = retsult;
            return retsult;
        }

        /// <summary>
        /// 关闭网口打印机，芯烨每次打印前打印
        /// </summary>
        /// <returns></returns>
        public bool CloseNetPrint()
        {
            bool retsult = false;
            try
            {
                switch (printscheme.brandId)
                {
                    case (int)GlobalEnumVars.PrinterBrand.XinYe:
                        LoadPOSDll.POS_Close();
                        break;
                    default:
                        if (PrinterManager.jsPrinter != null) PrinterManager.jsPrinter.CloseNetPor();
                        retsult = true;
                        break;
                }
            }
            catch (Exception ex) { }
            return retsult;
        }

        private void PrintLine()
        {
            try
            {
                switch (printscheme.brandId)
                {
                    case (int)GlobalEnumVars.PrinterBrand.XinYe:
                        PrinterManager.xyPrinter.SetRowHeight(0);
                        PrinterManager.xyPrinter.SetFontSize(1);
                        PrinterManager.xyPrinter.SetAlignMode(eTextAlignMode.Left);
                        PrinterManager.xyPrinter.PrintText("-".Repeat(menu.PageSize.CharCount() - 1));
                        //PrinterManager.xyPrinter.SetRowHeight(1);
                        break;
                    default:
                        PrinterManager.jsPrinter.SetRowHeight(0);
                        PrinterManager.jsPrinter.SetFontSize(1);
                        PrinterManager.jsPrinter.SetAlignMode(eTextAlignMode.Left);
                        PrinterManager.jsPrinter.PrintText("-".Repeat(menu.PageSize.CharCount() - 1));
                        PrinterManager.jsPrinter.SetRowHeight(1);
                        break;
                }
            }
            catch (Exception ex) { }
        }

        /// <summary>
        /// 设置行距
        /// </summary>
        /// <param name="bold"></param>
        /// <returns></returns>
        private bool SetRowHeight(int rowType)
        {
            try
            {
                switch (printscheme.brandId)
                {
                    case (int)GlobalEnumVars.PrinterBrand.XinYe:
                        if (!PrinterManager.xyPrinter.SetRowHeight(rowType)) return false;
                        break;
                    default:
                        if (!PrinterManager.jsPrinter.SetRowHeight(rowType)) return false;
                        break;
                }
            }
            catch (Exception ex) { }
            return true;
        }

        /// <summary>
        /// 打印机切纸SetBuzzing
        /// </summary>
        /// <param name="bold"></param>
        /// <returns></returns>
        private bool SetCutPaper()
        {
            try
            {
                switch (printscheme.brandId)
                {
                    case (int)GlobalEnumVars.PrinterBrand.XinYe:
                        LoadPOSDll.POS_CutPaper(0x00, 0x33);
                        break;
                    default:
                        PrinterManager.jsPrinter.Cut();
                        break;
                }
            }
            catch (Exception ex) { }
            return true;
        }

        /// <summary>
        /// 打印机峰鸣
        /// </summary>
        /// <param name="bold"></param>
        /// <returns></returns>
        private bool SetBuzzing()
        {
            try
            {
                switch (printscheme.brandId)
                {
                    case (int)GlobalEnumVars.PrinterBrand.XinYe:
                        PrinterManager.xyPrinter.SetBuzzing();
                        break;
                    default:
                        PrinterManager.jsPrinter.SetBuzzing();
                        break;
                }
            }
            catch (Exception ex)
            {
                //m_printer.CloseNetPor();
            }
            return true;
        }

        /// <summary>
        /// 设置字体
        /// </summary>
        /// <param name="bold"></param>
        /// <returns></returns>
        private bool SetFontSize(int FontSize)
        {
            try
            {
                switch (printscheme.brandId)
                {
                    case (int)GlobalEnumVars.PrinterBrand.XinYe:
                        if (!PrinterManager.xyPrinter.SetFontSize(FontSize)) return false;
                        break;
                    default:
                        if (!PrinterManager.jsPrinter.SetFontSize(FontSize)) return false;
                        break;
                }
            }
            catch (Exception ex)
            {
                //m_printer.CloseNetPor();
            }
            return true;
        }

        /// <summary>
        /// 设置对齐方式
        /// </summary>
        /// <param name="left"></param>
        /// <returns></returns>
        public bool SetAlignMode(eTextAlignMode alignmode)
        {
            try
            {
                switch (printscheme.brandId)
                {
                    case (int)GlobalEnumVars.PrinterBrand.XinYe:
                        if (!PrinterManager.xyPrinter.SetAlignMode(alignmode)) return false;
                        break;
                    default:
                        if (!PrinterManager.jsPrinter.SetAlignMode(alignmode)) return false;
                        break;
                }
            }
            catch (Exception ex)
            {
                //m_printer.CloseNetPor();
            }
            return true;
        }

        /// <summary>
        /// 打印文本.在调用本函数之前必须先调用正确的 设置字体、左边距
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public bool PrintText(string content)
        {
            try
            {
                switch (printscheme.brandId)
                {
                    case (int)GlobalEnumVars.PrinterBrand.XinYe:
                        if (string.IsNullOrEmpty(content)) content = " ";
                        if (!PrinterManager.xyPrinter.PrintText(content)) return false;
                        break;
                    default:
                        if (!PrinterManager.jsPrinter.PrintText(content)) return false;
                        break;
                }
            }
            catch (Exception ex)
            {
                //m_printer.CloseNetPor();
            }
            return true;
        }

        public bool PrintText(byte[] content)
        {
            try
            {
                switch (printscheme.brandId)
                {
                    case (int)GlobalEnumVars.PrinterBrand.XinYe:
                        if (!PrinterManager.xyPrinter.PrintText(content)) return false;
                        break;
                    default:
                        if (!PrinterManager.jsPrinter.PrintText(content)) return false;
                        break;
                }
            }
            catch (Exception ex)
            {
                //m_printer.CloseNetPor();
            }
            return true;
        }

        /// <summary>
        /// 通用打印机打印
        /// </summary>
        /// <param name="lines"></param>
        /// <returns></returns>
        private bool PrintLines(List<MenuLine> lines)
        {
            TypeAccessor accessors = null;
            List<string> members = new List<string>();
            if (MenuObj != null)
            {
                accessors = TypeAccessor.Create(typeof(MenuObject));
                var m = accessors.GetMembers();
                foreach (var t in m)
                {
                    members.Add(t.Name);
                }
            }

            foreach (MenuLine line in lines)
            {
                if (line.IsLine)
                {
                    PrintLine();
                }
                else
                {
                    if (!SetFontSize(line.FontSize)) return false;

                    if (line.Items.Count == 1)
                    {
                        var item = line.Items[0];

                        if (item.DataPropertyName.IsNullOrEmpty() && item.Text.IsNullOrEmpty())
                        {
                            if (!SetAlignMode(eTextAlignMode.Left)) return false;
                            if (!PrintText("")) return false;
                        }

                        if (item.DataPropertyName.IsNullOrEmpty() && item.Text.IsValid())
                        {
                            if (!SetAlignMode(item.TextAlign)) return false;
                            if (!PrintText(item.Text)) return false;
                        }

                        if (item.DataPropertyName.IsValid() && item.Text.IsNullOrEmpty())
                        {
                            if (!SetAlignMode(item.DataAlign)) return false;
                            string content = GetString(MenuObj, accessors, members, item.DataPropertyName);
                            if (!string.IsNullOrEmpty(content)) PrintText(content);
                        }

                        if (item.DataPropertyName.IsValid() && item.Text.IsValid())
                        {
                            byte[] bts = new byte[menu.PageSize.CharCount(line.FontSize)];
                            FillBlank(bts);
                            byte[] textBytes = Encoding.Default.GetBytes(item.Text);
                            string data = GetString(MenuObj, accessors, members, item.DataPropertyName);
                            byte[] dataBytes = Encoding.Default.GetBytes(data);

                            if (textBytes.Length > bts.Length || textBytes.Length + dataBytes.Length > bts.Length || dataBytes.Length > bts.Length)
                            {
                                if (!SetAlignMode(item.TextAlign)) return false;
                                if (!PrintText(item.Text)) return false;

                                if (!SetAlignMode(item.DataAlign)) return false;
                                if (!PrintText(data)) return false;
                            }
                            else
                            {
                                if (item.TextAlign == item.DataAlign)
                                {
                                    if (!SetAlignMode(item.TextAlign)) return false;
                                    if (!PrintText(item.Text + data)) return false;
                                }
                                else if (item.TextAlign == eTextAlignMode.Left)
                                {
                                    Array.Copy(textBytes, 0, bts, 0, textBytes.Length);

                                    if (item.DataAlign == eTextAlignMode.Middle)
                                        Array.Copy(dataBytes, 0, bts, textBytes.Length + (bts.Length - textBytes.Length - dataBytes.Length) / 2, dataBytes.Length);

                                    if (item.DataAlign == eTextAlignMode.Right)
                                        Array.Copy(dataBytes, 0, bts, bts.Length - dataBytes.Length, dataBytes.Length);

                                    if (!SetAlignMode(eTextAlignMode.Left)) return false;
                                    if (!PrintText(bts)) return false;
                                }
                                else
                                {
                                    if (!SetAlignMode(eTextAlignMode.Left)) return false;
                                    if (!PrintText(item.Text + data)) return false;
                                }
                            }
                        }
                    }
                    else
                    {
                        byte[] allBytes = new byte[menu.PageSize.CharCount(line.FontSize)];
                        FillBlank(allBytes);

                        int idx = 0;
                        foreach (var item in line.Items)
                        {
                            byte[] bts = new byte[item.Weight];
                            FillBlank(bts);

                            byte[] textBytes = Encoding.Default.GetBytes(item.Text);
                            string data = GetString(MenuObj, accessors, members, item.DataPropertyName);
                            byte[] dataBytes = Encoding.Default.GetBytes(data);

                            if (textBytes.Length + dataBytes.Length > bts.Length)
                            {
                                //ShowWarningTip(item.Text + data + "，字符串长度超过" + bts.Length);
                                bts = "X".Repeat(item.Weight).ToEnBytes(item.Weight);
                            }
                            else
                            {
                                if (item.TextAlign == item.DataAlign)
                                {
                                    int bidx = 0;
                                    if (item.TextAlign == eTextAlignMode.Middle)
                                        bidx = (bts.Length - textBytes.Length - dataBytes.Length) / 2;
                                    if (item.TextAlign == eTextAlignMode.Right)
                                        bidx = (bts.Length - textBytes.Length - dataBytes.Length);

                                    Array.Copy(textBytes, 0, bts, bidx, textBytes.Length);
                                    Array.Copy(dataBytes, 0, bts, bidx + textBytes.Length, dataBytes.Length);
                                }
                                else if (item.TextAlign == eTextAlignMode.Left)
                                {
                                    Array.Copy(textBytes, 0, bts, 0, textBytes.Length);

                                    if (item.DataAlign == eTextAlignMode.Middle)
                                        Array.Copy(dataBytes, 0, bts, textBytes.Length + (bts.Length - textBytes.Length - dataBytes.Length) / 2, dataBytes.Length);

                                    if (item.DataAlign == eTextAlignMode.Right)
                                        Array.Copy(dataBytes, 0, bts, bts.Length - dataBytes.Length, dataBytes.Length);
                                }
                                else
                                {
                                    Array.Copy(textBytes, 0, bts, 0, textBytes.Length);
                                    Array.Copy(dataBytes, 0, bts, textBytes.Length, dataBytes.Length);
                                }
                            }

                            Array.Copy(bts, 0, allBytes, idx, bts.Length);
                            idx += item.Weight + 1;
                        }

                        if (!SetAlignMode(eTextAlignMode.Left)) return false;
                        if (!PrintText(allBytes)) return false;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 打印数据到
        /// </summary>
        /// <param name="lines"></param>
        private void PrintData(List<MenuLine> lines)
        {
            try
            {
                TypeAccessor accessors = null;
                List<string> members = new List<string>();
                if (DataObj != null)
                {
                    accessors = TypeAccessor.Create(typeof(MenuObject));
                    var m = accessors.GetMembers();
                    foreach (var t in m)
                    {
                        members.Add(t.Name);
                    }
                }

                foreach (MenuLine line in lines)
                {
                    byte[] allBytes = new byte[menu.PageSize.CharCount(line.FontSize)];
                    FillBlank(allBytes);
                    int idx = 0;
                    foreach (var item in line.Items)
                    {
                        byte[] bts = new byte[item.Weight];
                        FillBlank(bts);

                        byte[] textBytes = Encoding.Default.GetBytes(item.Text);
                        if (textBytes.Length > bts.Length)
                        {
                            //ShowWarningTip(item.Text + "，字符串长度超过" + bts.Length);
                            bts = "X".Repeat(item.Weight).ToEnBytes(item.Weight);
                        }
                        else
                        {
                            int bidx = 0;
                            if (item.TextAlign == eTextAlignMode.Middle)
                                bidx = (bts.Length - textBytes.Length) / 2;
                            if (item.TextAlign == eTextAlignMode.Right)
                                bidx = (bts.Length - textBytes.Length);

                            Array.Copy(textBytes, 0, bts, bidx, textBytes.Length);
                        }

                        if (idx + bts.Length <= allBytes.Length)
                            Array.Copy(bts, 0, allBytes, idx, bts.Length);
                        idx += item.Weight + 1;
                    }
                    SetFontSize(line.FontSize);
                    SetAlignMode(eTextAlignMode.Left);

                    if (DataObj is IList list)
                    {
                        foreach (object o in list)
                        {
                            idx = 0;
                            FillBlank(allBytes);

                            string data = GetString(o, accessors, members, line.Items[0].DataPropertyName);
                            if (line.Items.Count == 1)
                            {
                                SetFontSize(line.FontSize);
                                SetAlignMode(eTextAlignMode.Left);
                                PrintText(data);
                                continue;
                            }

                            byte[] dataBytes = Encoding.Default.GetBytes(data);

                            if (menu.Multi || dataBytes.Length > allBytes.Length)
                            {
                                SetFontSize(line.FontSize);
                                SetAlignMode(eTextAlignMode.Left);
                                PrintText(data);
                            }
                            else
                            {
                                int bidx = 0;
                                byte[] bts = new byte[line.Items[0].Weight];

                                //如果打印的内容大于小票格式设定的内容，则截取一部分打印
                                if (dataBytes.Length > bts.Length)
                                {
                                    byte[] bdata = System.Text.Encoding.Default.GetBytes(data);//如果需要将中文当2个字符来取值，可以用下面的方法：
                                    data = System.Text.Encoding.Default.GetString(bdata, 0, bts.Length - 1).Replace("?", "");
                                    dataBytes = Encoding.Default.GetBytes(data);
                                }

                                FillBlank(bts);
                                if (line.Items[0].DataAlign == eTextAlignMode.Middle)
                                    bidx = (bts.Length - dataBytes.Length) / 2;
                                if (line.Items[0].DataAlign == eTextAlignMode.Right)
                                    bidx = (bts.Length - dataBytes.Length);

                                Array.Copy(dataBytes, 0, bts, bidx, dataBytes.Length);
                                Array.Copy(bts, 0, allBytes, 0, bts.Length);
                            }

                            idx += line.Items[0].Weight + 1;
                            for (int i = 1; i < line.Items.Count; i++)
                            {
                                var item = line.Items[i];
                                byte[] bts = new byte[item.Weight];
                                FillBlank(bts);
                                data = GetString(o, accessors, members, item.DataPropertyName);
                                dataBytes = Encoding.Default.GetBytes(data);

                                //如果打印的内容大于小票格式设定的内容，则截取一部分打印
                                if (dataBytes.Length > bts.Length)
                                {
                                    byte[] bdata = System.Text.Encoding.Default.GetBytes(data);//将中文当2个字符来取值：
                                    data = System.Text.Encoding.Default.GetString(bdata, 0, bts.Length - 1).Replace("?", ""); ;
                                    dataBytes = Encoding.Default.GetBytes(data);
                                }

                                int bidx = 0;
                                if (item.DataAlign == eTextAlignMode.Middle)
                                    bidx = (bts.Length - dataBytes.Length) / 2;
                                if (item.DataAlign == eTextAlignMode.Right)
                                    bidx = (bts.Length - dataBytes.Length);

                                Array.Copy(dataBytes, 0, bts, bidx, dataBytes.Length);
                                Array.Copy(bts, 0, allBytes, idx, bts.Length);

                                idx += item.Weight + 1;
                            }
                            SetFontSize(line.FontSize);
                            SetAlignMode(eTextAlignMode.Left);
                            PrintText(allBytes);
                        }

                        if (DataTotalObj != null)
                        {
                            idx = 0;
                            FillBlank(allBytes);

                            foreach (var item in line.Items)
                            {
                                byte[] bts = new byte[item.Weight];
                                FillBlank(bts);

                                string data = GetString(DataTotalObj, accessors, members, item.DataPropertyName);
                                byte[] dataBytes = Encoding.Default.GetBytes(data);
                                //如果打印的内容大于小票格式设定的内容，则截取一部分打印
                                if (dataBytes.Length > bts.Length)
                                {
                                    byte[] bdata = System.Text.Encoding.Default.GetBytes(data);//将中文当2个字符来取值：
                                    data = System.Text.Encoding.Default.GetString(bdata, 0, bts.Length - 1).Replace("?", ""); ;
                                    dataBytes = Encoding.Default.GetBytes(data);
                                }

                                int bidx = 0;
                                if (item.TextAlign == eTextAlignMode.Middle)
                                    bidx = (bts.Length - dataBytes.Length) / 2;
                                if (item.TextAlign == eTextAlignMode.Right)
                                    bidx = (bts.Length - dataBytes.Length);

                                Array.Copy(dataBytes, 0, bts, bidx, dataBytes.Length);
                                Array.Copy(bts, 0, allBytes, idx, bts.Length);
                                idx += item.Weight + 1;
                            }
                            SetFontSize(line.FontSize);
                            SetAlignMode(eTextAlignMode.Left);
                            PrintText(allBytes);
                        }
                    }
                }
            }
            catch { }
        }

        private string GetString(object obj, TypeAccessor accessors, List<string> members, string dataPropertyName)
        {
            if (dataPropertyName.IsNullOrEmpty()) return "";
            try
            {
                if (accessors != null && members.IndexOf(dataPropertyName) >= 0)
                    return accessors[obj, dataPropertyName].ToString();
            }
            catch { }
            return "XX";
        }

        private void FillBlank(byte[] bts)
        {
            for (int i = 0; i < bts.Length; i++)
            {
                bts[i] = 32;
            }
        }

        #endregion

        /// <summary>
        /// 计算打印的合计数
        /// </summary>
        /// <param name="taskdetails"></param>
        private void SumPrintTaskDetail(List<corecmsprinttaskdetail> taskdetails)
        {
            var taskdetail0 = taskdetails[0];
            var sumQuantity = taskdetails.Sum(p => p.quantity);
            var sumAmount = taskdetails.Sum(p => p.amount);
            var sumRealAmount = taskdetails.Sum(p => p.realAmount);
            var sumTaskAmount = taskdetails.Sum(p => p.taskAmount);
            var sumFeedAmount = taskdetails.Sum(p => p.feedAmount);
            var sumAllAmount = taskdetails.Sum(p => p.allAmount);
            var sumDisAmount = taskdetail0.sumAmount + taskdetail0.sumTaskAmount + taskdetail0.sumFeedAmount - taskdetail0.sumAllAmount;

            int rowId = 1;
            foreach (var item in taskdetails)
            {
                item.rowId = rowId;
                item.sumQuantity = sumQuantity;
                item.sumAmount = sumAmount;
                item.sumRealAmount = sumRealAmount;
                item.sumTaskAmount = sumTaskAmount;
                item.sumFeedAmount = sumFeedAmount;
                item.sumAllAmount = sumAllAmount;
                item.sumDisAmount = sumDisAmount;
                rowId++;
            }
        }

        /// <summary>
        /// 第4步:把打印明细发送到厨房打印（汇总打印)
        /// </summary>        
        /// <param name="taskdetails"></param>
        public bool SetPrintKitchenByList(List<corecmsprinttaskdetail> taskdetails, corecmsprintbilltemplate billtemplate)
        {
            if ((taskdetails == null) || (taskdetails.Count == 0)) return true;
            ClearPrintObject();
            DateTime dateTime = DateTime.Now;
            try
            {
                if ((billtemplate == null) || (string.IsNullOrEmpty(billtemplate.content))) return true;
                menu = Json.Deserialize<Menu>(billtemplate.content);

                SumPrintTaskDetail(taskdetails);

                var taskdetail = taskdetails[0];
                var obj = GetMenuObject(taskdetail);
                MenuObj = obj;

                int rowId = 1;
                decimal allQuantity = 0;
                decimal allAmount = 0;
                List<MenuObject> list = new List<MenuObject>();
                foreach (var item in taskdetails)
                {
                    item.printStatus = (int)GlobalEnumVars.PrintStatus.Success;
                    item.updataTime = dateTime;
                    list.Add(GetMenuObject(item));
                    if (!string.IsNullOrEmpty(item.taskTitle))
                        list.Add(GetMenuObjectSub(billtemplate.taskSign.ObjToString() + "做法：" + item.taskTitle));
                    if (!string.IsNullOrEmpty(item.feedTitle))
                        list.Add(GetMenuObjectSub(billtemplate.taskSign.ObjToString() + "加料：" + item.feedTitle));
                    if (!string.IsNullOrEmpty(item.detailRemark))
                        list.Add(GetMenuObjectSub(billtemplate.taskSign.ObjToString() + "备注：" + item.detailRemark));
                    allQuantity += item.quantity;
                    allAmount += item.allAmount;
                    rowId++;
                }

                DataObj = list;
                //DataTotalObj = obj;

                var bl = SetPrintData(MenuObj, DataObj, DataTotalObj, menu);
                if (!bl)
                {
                    foreach (var item in taskdetails)
                    {
                        item.printStatus = (int)GlobalEnumVars.PrintStatus.Fail;
                    }
                }
                new corecmsprinttaskdetailServices().UpdateRange(taskdetails);
                return bl;
            }
            catch { }
            return false;
        }

        /// <summary>
        /// 厨房打印（一菜一单)
        /// </summary>        
        /// <param name="taskdetails"></param>
        public bool SetPrintKitchenByOne(List<corecmsprinttaskdetail> taskdetails, corecmsprintbilltemplate billtemplate)
        {
            if ((taskdetails == null) || (taskdetails.Count == 0)) return true;
            ClearPrintObject();
            try
            {
                if ((billtemplate == null) || (string.IsNullOrEmpty(billtemplate.content))) return true;
                menu = Json.Deserialize<Menu>(billtemplate.content);
                var ret = true;
                foreach (var taskdetail in taskdetails)
                {
                    var obj = GetMenuObject(taskdetail);
                    MenuObj = obj;
                    List<MenuObject> list = new List<MenuObject> { obj };
                    DataObj = list;
                    //DataTotalObj = obj;

                    var bl = SetPrintData(MenuObj, DataObj, DataTotalObj, menu);
                    if (!bl)
                    {
                        ret = false;
                        taskdetail.printStatus = (int)GlobalEnumVars.PrintStatus.Fail;
                    }
                    else
                        taskdetail.printStatus = (int)GlobalEnumVars.PrintStatus.Success;
                    taskdetail.updataTime = DateTime.Now;
                    new corecmsprinttaskdetailServices().UpdateAsync(taskdetail);
                    Thread.Sleep(500);
                }
                return ret;
            }
            catch { }
            return true;
        }

        /// <summary>
        /// 预结算单（汇总打印)
        /// </summary>        
        /// <param name="taskdetails"></param>
        public void SetPrintPrePayment(corecmsfoodorderingmaster orderMaster)
        {
            var schemedetail = printscheme.printschemedetails.Find(p => p.billtypeId == (int)GlobalEnumVars.PrintbillType.PrePayment);
            if (schemedetail == null) return;
            var billtemplate = schemedetail.billtemplate;
            if (billtemplate == null) return;

            //记录已预打单
            new corecmsfoodorderingmasterServices().Update(a => new corecmsfoodorderingmaster()
            {
                status = (int)GlobalEnumVars.TableStatus.PreSettled,
            }, a => a.orderId == orderMaster.orderId && a.payStatus == (int)GlobalEnumVars.OrderPayStatus.UnPay);

            if (printscheme.sendPrintWay == (int)GlobalEnumVars.SendPrintWay.Command)
            {
                //端口打印
                if (string.IsNullOrEmpty(billtemplate.content)) return;
                SetPrintPrePaymentIP(orderMaster, billtemplate);
            }
            else
            {
                //驱动打印
                if (string.IsNullOrEmpty(billtemplate.reportFile) && string.IsNullOrEmpty(billtemplate.reportData)) return;
                new ReportServices().SetPrintPrePayment(orderMaster, billtemplate, false, printscheme);
            }
        }

        /// <summary>
        /// 收银交班单
        /// </summary>        
        /// <param name="taskdetails"></param>
        public void SetPrintClassBill(ClassDataDto classData, bool isPrintPreview = false)
        {
            var schemedetailList = new corecmsprintschemedetailServices().SelectByBilltypeId((int)GlobalEnumVars.PrintbillType.ClassBill);
            if (schemedetailList == null) return;
            var schemedetail = schemedetailList.First();
            var billtemplate = schemedetail.billtemplate;
            if (billtemplate == null) return;
            //驱动打印
            if (string.IsNullOrEmpty(billtemplate.reportFile)) return;
            new ClassBillServices().SetPrintClassBill(billtemplate, classData, isPrintPreview);
        }

        /// <summary>
        /// 收银交班单
        /// </summary>        
        /// <param name="taskdetails"></param>
        public void SetPrintClassDesign()
        {
            var schemedetailList = new corecmsprintschemedetailServices().SelectByBilltypeId((int)GlobalEnumVars.PrintbillType.ClassBill);
            if (schemedetailList == null) return;
            var schemedetail = schemedetailList.First();
            var billtemplate = schemedetail.billtemplate;
            if (billtemplate == null) return;
            //驱动打印
            if (string.IsNullOrEmpty(billtemplate.reportFile)) return;
            new ReportServices().SetDesignReport(billtemplate);
        }

        /// <summary>
        /// 会员充值小票
        /// </summary>        
        /// <param name="taskdetails"></param>
        public void SetUserDepositBill(corecmsuserbalance _userbalance, corecmsuser _userInfo, bool isPrintPreview = false)
        {
            var schemedetailList = new corecmsprintschemedetailServices().SelectByBilltypeId((int)GlobalEnumVars.PrintbillType.UserDeposit);
            if (schemedetailList == null) return;
            foreach (var schemedetail in schemedetailList)
            {
                if (schemedetail.billtemplate != null)
                {
                    if (string.IsNullOrEmpty(schemedetail.billtemplate.reportFile)) return;
                    new ClassBillServices().SetUserDepositBill(schemedetail.billtemplate, _userbalance, _userInfo, isPrintPreview);
                }
            }

        }

        /// <summary>
        /// 预结算单-IP（汇总打印)
        /// </summary>        
        /// <param name="taskdetails"></param>
        public void SetPrintPrePaymentIP(corecmsfoodorderingmaster orderMaster, corecmsprintbilltemplate billtemplate)
        {
            ClearPrintObject();
            try
            {
                if ((billtemplate == null) || (string.IsNullOrEmpty(billtemplate.content))) return;
                menu = Json.Deserialize<Menu>(billtemplate.content);

                var taskdetails = new corecmsprinttaskdetailServices().QueryFromOrdering(orderMaster, billtemplate);
                if ((taskdetails == null) || (taskdetails.Count == 0) || (billtemplate == null)) return;

                SumPrintTaskDetail(taskdetails);

                var taskdetail0 = taskdetails[0];
                var obj = GetMenuObject(taskdetail0);
                MenuObj = obj;

                List<MenuObject> list = new List<MenuObject>();
                foreach (var item in taskdetails)
                {
                    list.Add(GetMenuObject(item));
                }

                DataObj = list;

                var bl = SetPrintData(MenuObj, DataObj, DataTotalObj, menu);
            }
            catch { }
        }

        /// <summary>
        /// 结账单打印（汇总打印)
        /// </summary>        
        /// <param name="taskdetails"></param>
        public void SetPrintSettlement(corecmsfoodordermaster orderMaster, bool isPrintPreview = false)
        {
            //var schemedetail = printscheme.printschemedetails.Find(p => p.billtypeId == (orderMaster.sourceType != 2 ? (int)GlobalEnumVars.PrintbillType.Settlement : (int)GlobalEnumVars.PrintbillType.takeOut));
            var schemedetailList = new corecmsprintschemedetailServices().SelectByBilltypeId((int)GlobalEnumVars.PrintbillType.Settlement);
            if (schemedetailList == null) return;
            foreach (var schemedetail in schemedetailList)
            {
                if (schemedetail.billtemplate != null)
                {
                    if (schemedetail.printscheme.sendPrintWay == (int)GlobalEnumVars.SendPrintWay.Command)
                    {
                        //端口打印
                        if (string.IsNullOrEmpty(schemedetail.billtemplate.content)) return;
                        SetPrintSettlementIP(orderMaster, schemedetail.billtemplate);
                    }
                    else
                    {
                        //驱动打印
                        if (string.IsNullOrEmpty(schemedetail.billtemplate.reportFile)) return;
                        new ReportServices().SetPrintSettlement(orderMaster, schemedetail.billtemplate, isPrintPreview, schemedetail.printscheme);
                    }
                }                
            }
        }

        /// <summary>
        /// 批发送货单
        /// </summary>        
        /// <param name="taskdetails"></param>
        public void SetPrintOrdering(corecmsfoodordermaster orderMaster, bool isPrintPreview = false)
        {            
            var schemedetailList = new corecmsprintschemedetailServices().SelectByBilltypeId((int)GlobalEnumVars.PrintbillType.FoodList);
            if ((schemedetailList == null) || (schemedetailList.Count == 0)) return;

            foreach (var schemedetail in schemedetailList)
            {
                if (schemedetail.billtemplate != null)
                {
                    if (schemedetail.printscheme.sendPrintWay == (int)GlobalEnumVars.SendPrintWay.Command)
                    {
                        //端口打印
                        if (string.IsNullOrEmpty(schemedetail.billtemplate.content)) return;
                        //SetPrintSettlementIP(orderMaster, schemedetail.billtemplate);
                    }
                    else
                    {
                        //驱动打印
                        if (string.IsNullOrEmpty(schemedetail.billtemplate.reportFile)) return;
                        new ReportServices().SetPrintSettlement(orderMaster, schemedetail.billtemplate, isPrintPreview, schemedetail.printscheme);
                    }
                }
            }
        }

        /// <summary>
        /// 标签打印
        /// </summary>        
        /// <param name="taskdetails"></param>
        public void SetPrintLabel(corecmsfoodordermaster orderMaster, bool isPrintPreview = false)
        {
            var schemedetailList = new corecmsprintschemedetailServices().SelectByBilltypeId((int)GlobalEnumVars.PrintbillType.Label);
            if ((schemedetailList == null) || (schemedetailList.Count == 0)) return;
            new ReportServices().SetPrintLabel(schemedetailList, orderMaster, isPrintPreview);
        }

        /// <summary>
        /// 标签打印
        /// </summary>        
        /// <param name="taskdetails"></param>
        public bool SetPrintLabelFromOrder(corecmsfoodorderingmaster orderMaster, corecmsfoodordering ordering, bool isPrintPreview = false)
        {
            var schemedetailList = new corecmsprintschemedetailServices().SelectByBilltypeId((int)GlobalEnumVars.PrintbillType.Label);
            if ((schemedetailList == null) || (schemedetailList.Count == 0)) return false;
            return  new ReportServices().SetPrintLabelFromOrder(schemedetailList, orderMaster, ordering, isPrintPreview);           
        }

        /// <summary>
        /// 结账单打印_IP（汇总打印)
        /// </summary>        
        /// <param name="taskdetails"></param>
        public void SetPrintSettlementIP(corecmsfoodordermaster orderMaster, corecmsprintbilltemplate billtemplate)
        {
            ClearPrintObject();
            try
            {
                if (string.IsNullOrEmpty(billtemplate.content)) return;
                menu = Json.Deserialize<Menu>(billtemplate.content);

                var taskdetails = new corecmsprinttaskdetailServices().QueryFromOrderDetail(orderMaster, billtemplate);
                if ((taskdetails == null) || (taskdetails.Count == 0)) return;

                SumPrintTaskDetail(taskdetails);

                var taskdetail0 = taskdetails[0];
                var obj = GetMenuObject(taskdetail0);
                MenuObj = obj;

                List<MenuObject> list = new List<MenuObject>();
                foreach (var item in taskdetails)
                {
                    list.Add(GetMenuObject(item));
                }

                DataObj = list;

                var bl = SetPrintData(MenuObj, DataObj, DataTotalObj, menu);
            }
            catch { }
        }


        /// <summary>
        /// 标签打印_IP
        /// </summary>        
        /// <param name="taskdetails"></param>
        public void SetPrintLabelIP(corecmsfoodordermaster orderMaster, corecmsprintbilltemplate billtemplate)
        {
            ClearPrintObject();
            try
            {
                if (string.IsNullOrEmpty(billtemplate.content)) return;
                menu = Json.Deserialize<Menu>(billtemplate.content);

                var taskdetails = new corecmsprinttaskdetailServices().QueryFromOrderDetail(orderMaster, billtemplate);
                if ((taskdetails == null) || (taskdetails.Count == 0)) return;

                SumPrintTaskDetail(taskdetails);

                var taskdetail0 = taskdetails[0];
                var obj = GetMenuObject(taskdetail0);
                MenuObj = obj;

                List<MenuObject> list = new List<MenuObject>();
                foreach (var item in taskdetails)
                {
                    list.Add(GetMenuObject(item));
                }

                DataObj = list;

                var bl = SetPrintData(MenuObj, DataObj, DataTotalObj, menu);
            }
            catch { }
        }

        /// <summary>
        /// 客户点菜单（原单打印)
        /// </summary>        
        /// <param name="taskdetails"></param>
        public void SetPrintOrdering(List<corecmsprinttaskdetail> taskdetails
            , corecmsfoodorderingmaster orderingmaster)
        {
            if (printscheme.printschemedetails == null) return;
            var schemedetail = printscheme.printschemedetails.Find(p => p.billtypeId == (int)GlobalEnumVars.PrintbillType.FoodList && p.selectedFlag == true);
            if (schemedetail == null) return;
            var billtemplate = schemedetail.billtemplate;
            if (billtemplate == null) return;
            //暂不能IP打印。前台用IP打印，会与厨打监控冲突
            //if (printscheme.sendPrintWay == (int)GlobalEnumVars.SendPrintWay.Command)
            //{
            //    //端口打印
            //    if (string.IsNullOrEmpty(billtemplate.content)) return;
            //    SetPrintOrderingIP(taskdetails, billtemplate);
            //}
            //else
            //{
            //驱动打印
            if (string.IsNullOrEmpty(billtemplate.reportFile)) return;
            new ReportServices().SetPrinOrdering(taskdetails, billtemplate, orderingmaster, false, printscheme);
        }

        /// <summary>
        /// 客户点菜单_IP（原单打印)
        /// </summary>        
        /// <param name="taskdetails"></param>
        public void SetPrintOrderingIP(List<corecmsprinttaskdetail> taskdetails, corecmsprintbilltemplate billtemplate)
        {
            ClearPrintObject();
            try
            {
                if ((billtemplate == null) || (string.IsNullOrEmpty(billtemplate.content))) return;
                menu = Json.Deserialize<Menu>(billtemplate.content);

                if ((taskdetails == null) || (taskdetails.Count == 0)) return;

                SumPrintTaskDetail(taskdetails);

                var taskdetail0 = taskdetails[0];
                var obj = GetMenuObject(taskdetail0);
                MenuObj = obj;

                List<MenuObject> list = new List<MenuObject>();
                foreach (var item in taskdetails)
                {
                    list.Add(GetMenuObject(item));
                }

                DataObj = list;

                var bl = SetPrintData(MenuObj, DataObj, DataTotalObj, menu);
            }
            catch { }
        }

    }
}
